import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Injectable()
export class CookiesService {

  constructor(
    @Inject(DOCUMENT) private doc: Document
  ) { }

  /**
   * Set Cookie
   * @param c_name, string, Cookie Name
   * @param value, string, Cookie Value
   * @param expiredays, string or number, expired days
   */
  public setCookies (c_name: string, value: any, expiredays: string | number) {
    const exdate: any = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    this.doc.cookie = c_name + '=' + encodeURI(value) + ((expiredays === null) ? '' : ';expires=' + exdate.toString() + ';path=/');
  }

  /**
   * 获取Cookie值
   * @param c_name , string, Cookie key
   */
  public getCookie (c_name: string) {
    if (this.doc.cookie.length > 0) {
      let c_start = this.doc.cookie.indexOf(c_name + '=');
      if (c_start !== -1) {
          c_start = c_start + c_name.length + 1;
          let c_end = this.doc.cookie.indexOf(';', c_start);
          if (c_end === -1) {
            c_end = this.doc.cookie.length;
          }
          return encodeURI(this.doc.cookie.substring(c_start, c_end));
      }
    }
    return '';
  }

  /**
   * 删除某个Cookie
   * @param c_name , string, Cookie key
   */
  public deleteCookie (c_name: string) {
    this.setCookies(c_name, '', -1);
  }

  /**
   * 一键删除所有Cookie
   */
  public deleteAllCookies () {
    const cookieArray = this.doc.cookie.split(';'); // 将所有cookie分割为key->value
    const keyArray = [];
    for (let i = 0; i < cookieArray.length; i++) {
      keyArray.push(cookieArray[i].split('=')[0]);
    }
    for (let j = 0; j < keyArray.length; j++) {
        this.deleteCookie(keyArray[j]);
    }

  }

  /**
   * 检查是否存在某个Cookie
   * @param c_name ,string, Cookie name
   */
  public isSetCookie (c_name: string) {
    const info = this.getCookie(c_name);
    if (info === '') {
      return false;
    } else {
        return info;
    }
  }

}